package cn.edu.gcu.lost.sys.service;

import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.RuntimeSqlException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.gcu.lost.sys.dao.UserDao;
import cn.edu.gcu.lost.sys.entity.User;
import cn.edu.gcu.lost.sys.util.PasswordUtils;

@Service
@Transactional(readOnly = true)
public class UserService {

    private static int NO_CHANGE = 0;

    @Autowired
    private UserDao userDao;

    public Object findList(String search, int start, int size) {
        return userDao.findList(search, start, size);
    }

    @Transactional(readOnly = false, rollbackFor = SQLException.class)
    public boolean save(User user) throws SQLException {
        if (StringUtils.isBlank(user.getId())) {
            user.preInsert();
            user.setPassword(PasswordUtils.encrypt(user.getPassword().trim()));
            if (isExistByNo(user) || StringUtils.isBlank(user.getRole().getId().trim()) || userDao.insert(user) ==
					NO_CHANGE)
                return false;
            if (userDao.addRole(user) == NO_CHANGE)
                throw new RuntimeSqlException("为用户添加角色异常");
        } else {
            user.preUpdate();
            if (StringUtils.isNotBlank(user.getPassword())) {
                user.setPassword(PasswordUtils.encrypt(user.getPassword()));
            }
            if (userDao.update(user) == NO_CHANGE)
                return false;
            if (user.getRole() != null && StringUtils.isNotBlank(user.getRole().getId())) {
                if (userDao.removeRole(user) == NO_CHANGE || userDao.addRole(user) == NO_CHANGE)
                    throw new RuntimeSqlException("为用户修改角色异常");
            }
        }
        return true;
    }

    @Transactional(readOnly = false)
    public boolean delete(User user) {
        if (userDao.isExist(user) == 0) {
            return false;
        } else if (userDao.delete(user) == NO_CHANGE) {
            return false;
        } else {
            userDao.removeRole(user);
            return true;
        }
    }

    public boolean updatePassword(User user) {
        user.preUpdate();
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        return userDao.updatePassword(user) > 0;
    }

    public boolean updateSelf(User user) {
        // TODO Auto-generated method stub
        user.preUpdate();
        return userDao.updateSelf(user) > 0;
    }

    public boolean isExistByNo(User user) {
        return userDao.isExistByNo(user) > 0;
    }

    public Integer countAllNum(String search) {
        return userDao.countAllNum(search);
    }

    public User findDetail(User user) {
        return userDao.findDetail(user);
    }
}
